var rp = require('request-promise');
var zlib = require('zlib');
var StatsD = require('node-statsd');

var token = "";
var succes = false;
var client = new StatsD(host = process.env.GRAPHITE_PORT_8125_UDP_ADDR, prot = 8125);

function start() {
    rp.defaults({
        jar: true,
    })

    mainLoop();

    setInterval(mainLoop, 15000);
}

function mainLoop() {
    login();
}

function login() {
    if (token != "" && succes) {
        getMemory();
        return;
    }
    console.log("New login request - " + new Date())
    let options = {
        uri: 'https://screeps.com/api/auth/signin',
        json: true,
        method: 'POST',
        body: {
            email: process.env.SCREEPS_EMAIL,
            password: process.env.SCREEPS_PASSWORD,
        }
    }
    rp(options).then((x) => {
        token = x.token
        getMemory()
    })
}

function getMemory() {
    succes = false
    let options = {
        uri: 'https://screeps.com/api/user/memory',
        method: 'GET',
        json: true,
        resolveWithFullResponse: true,
        headers: {
            "X-Token": token,
            "Content-Type": "application/x-www-form-urlencoded",
        },
        qs: {
            path: process.env.SCREEPS_PATH,
            shard: process.env.SCREEPS_SHARD
        }
    }

    rp(options).then((x) => {
        token = x.headers['x-token'];
        if (!x.body.data)
            return;
        let data = x.body.data.split('gz:')[1];
        let finalData = JSON.parse(zlib.gunzipSync(Buffer.from(data, 'base64')).toString())
        succes = true
        report(finalData)
    })
}

function report(data, prefix = "") {
    if (prefix === '')
        console.log("Pushing to gauges - " + new Date())
    for (let k in data) {
        let v = data[k];
        if (typeof v == 'object')
            report(v, prefix + k + '.');
        else {
            //console.log(prefix + k);
            //console.log(v)
            client.gauge(prefix + k, v)
        }
    }
}

start();